package com.nc.shop.service.service.impl;

import com.nc.shop.service.dao.CarDao;
import com.nc.shop.service.dao.RepertoryDao;
import com.nc.shop.service.dao.ShopDao;
import com.nc.shop.service.model.entity.CarEntity;
import com.nc.shop.service.model.entity.RepertoryEntity;
import com.nc.shop.service.model.entity.ShopEntity;
import com.nc.shop.service.service.CarService;
import com.nc.shop.service.service.RepertoryService;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.smartcardio.Card;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Service
public class CarServiceImpl implements CarService {
    @Autowired
    ShopDao shopDao;
    @Autowired
    CarDao carDao;
    @Autowired
    RepertoryService repertoryService;

    @Override
    @Transactional
    public RetResult insert(String userId, String shopId, Integer number) {
        Optional<ShopEntity> shop = shopDao.findById(shopId);
        if (shop.isPresent() && shop.get().getRepertory() - number >= 0) {
            CarEntity carEntity = new CarEntity();
            carEntity.setMoney(shop.get().getPrice().multiply(new BigDecimal(number)));
            carEntity.setPrice(shop.get().getPrice());
            carEntity.setNumber(number);
            carEntity.setShopId(shopId);
            carEntity.setUserId(userId);
            carDao.save(carEntity);
        }
        return RetResponse.makeErrRsp("商品不存在或库存不足！");
    }

    @Override
    public RetResult out(String id) {
        Optional<CarEntity> car = carDao.findById(id);
        if (!car.isPresent()) {
            return RetResponse.makeErrRsp("购物车不存在当前商品");
        } else {
            carDao.delete(car.get());
            return RetResponse.makeOKRsp();
        }
    }
}
